/*
 * Copyright 2007-2010 kingbi.
 * Creator: Janins
 */
package com.kingbi.system.role.service;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.beanutils.BasicDynaBean;

import com.kingbi.system.function.dao.FunctionDao;
import com.kingbi.system.role.dao.RoleDao;
import com.kingbi.system.role.dao.RoleQuery;
import com.kingbi.system.role.model.RoleModel;
import com.kingbi.system.roleFunction.dao.RoleFunctionDao;
import com.kingbi.system.roleFunction.model.RoleFunctionModel;
import com.kingbi.system.roleFunction.model.RoleFunction_ID;

/**
 * @author mouzb
 * 
 */
public class RoleServiceImpl implements RoleService
{

    private RoleDao roleDao;

    private RoleFunctionDao roleFunctionDao;

    public void setRoleDao(RoleDao thisDao)
    {
        roleDao = thisDao;
    }

    public void setRoleFunctionDao(RoleFunctionDao funDao)
    {
        this.roleFunctionDao = funDao;
    }

    public void saveRole(RoleModel roleModel, String roleFunRight) throws Exception
    {
        try
        {
            roleDao.deleteBySQL("DELETE from P_ROLE_FUNCTION WHERE ROLE_CODE = '" + roleModel.getRoleCode()+"'");
        }
        catch (Exception e)
        {
            throw new Exception("");
        }
        
        if(roleFunRight != null && !roleFunRight.equals("") && !roleFunRight.equals("null"))
        {
            String[] funRight = roleFunRight.replaceAll(",", "※").split("※");

            if(funRight.length > 1)
            {
                String funRW = "";
                for (int i = 0; i < funRight.length; i++)
                {
                    RoleFunctionModel roleFunModel = new RoleFunctionModel();
                    funRW = funRight[i];
                    if(!funRW.toLowerCase().equals("undefined"))
                    {
                         String[] funcr = funRW.split("~");
                         RoleFunction_ID roleFunID = new  RoleFunction_ID();
                         //设置角色编码
                         roleFunID.setRoleCode(roleModel.getRoleCode());
                        //设置功能编码                        
                         roleFunID.setFunctionCode(funcr[0]);
                         roleFunModel.setRoleFunID(roleFunID);
                        //设置功能权限
                         if(funcr[1]!=null)
                         {
                             if(funcr[1].equals("-1"))
                             {
                                 roleFunModel.setRoleRight("");
                             }
                             else
                             {
                                 roleFunModel.setRoleRight(funcr[1]);
                             }
                         }
                        
                         //添加关联数据库
                         roleFunctionDao.add_update(roleFunModel);
                    }
                }
            }

        }
        else
        {
            throw new Exception("ddd");
        }
        try
        {
        roleDao.save(roleModel);
        }catch(Exception e){
    	e.printStackTrace();
    }
        }
    
    
    public int getMaxId (){
        
		StringBuffer queryUserSql = new StringBuffer();
		queryUserSql.append("SELECT MAX(ROLE_ID) max_role_id FROM p_role");
		String maxRoleId = "";
		try {
			List<Object> objList = roleDao.findBySQL(queryUserSql.toString(), null);
			if(!objList.isEmpty()){
    			BasicDynaBean bean = null;
    			for(int i=0; i<objList.size(); i++){
    				bean = (BasicDynaBean) objList.get(i);
    				maxRoleId = bean.get("max_role_id")!=null ? bean.get("max_role_id").toString():"0";
    			}
    		}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		int maxId = Integer.parseInt(maxRoleId);
		
		return maxId;       
	
}

    public RoleModel loadRole(int roleID)
    {
        return roleDao.findById(roleID);
    }
    

    public List<RoleModel> loadRoleByCode(String roleCode)
    {
        return roleDao.findCmd("loadRoleByCode", new Object[] { roleCode }, -1, -1);
    }

    public void deleteRole(int roleID)
    {
        roleDao.delete(roleDao.findById(roleID));
    }

    public List<RoleModel> listRole(RoleModel roleModel, int start, int max)
    {
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.doSearchQuery(roleModel);
        return roleDao.findByHQL(roleQuery.getSearch_query_bud().toString(), roleQuery.getParams(),
                start, max);
    }

    public List<RoleModel> loadVerifyRole(int page, int max, Object[] sql_params)
    {
        return roleDao.findCmd("loadVerifyPack", sql_params, page, max);
    }

    public long queryCount(RoleModel roleModel)
    {
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.doSearchQuery(roleModel);
        return roleDao.getCountByHQL(roleQuery.getSearch_count_bud().toString(), roleQuery
                .getParams());
    }
    
    /**
     * 查询最大的角色编号
     * @throws SQLException 
     */
    public String getMaxRoleId() throws SQLException{
    	StringBuffer sbsql = new StringBuffer();
    	sbsql.append(" select ");
    	sbsql.append(" case when aa.max_role_code is null then  'R0001' else aa.max_role_code end max_role_code");
    	sbsql.append(" from (");
    	sbsql.append(" select concat('R',lpad(cast(substr(max(pr.role_code),2,4) as unsigned) +1,4,'0')) AS max_role_code  from p_role pr");
    	sbsql.append(" ) aa");
    	
    	String maxRoleId = "";
    	List<Object> objList = roleDao.findBySQL(sbsql.toString(), null);
    	if(objList.size()-1 ==0 ){
    		BasicDynaBean bean = (BasicDynaBean) objList.get(0);
    		maxRoleId = bean.get("max_role_code")!=null?bean.get("max_role_code").toString():"";
    	}
    	return maxRoleId;
    }

}
